local json = require("ap.json")
local base = require("ap.acctl_base")
local lib = require("ap.acctl_lib")

local function entry_exist(cmd)
	return lib.capture(cmd)
end

local function section_name(cmd)
	local f = assert(io.popen(cmd .. " 2>/dev/null", 'r'))
	local s = assert(f:read('*line'))
	f:close()
	return s
end

local function travel_section(table, cmd, section)
	status[table][section]={}
	for i,v in ipairs(cmd.params) do 
		local tmp
		tmp = string.gsub(cmd.get, "<section>", section)
		tmp = string.gsub(tmp, "<option>", v)
		status[table][section][v] = lib.capture(tmp)
	end
end

local function fillstatus(table, cmd, section)
	local i = 0

	if section then
		travel_section(table, cmd, section)
		return
	end

	while entry_exist(string.gsub(cmd.stat, "<num>", i)) do
		section = section_name(string.gsub(cmd.section, "<num>", i)) 
		travel_section(table, cmd, section)
		i = i+1
	end
end

function apstatus()
	local status = {device={}, network={}, wireless={}, switch={}, vlan={}}
	return function() 
		status.device.model = lib.capture(system.get)
		fillstatus("network", network)
		fillstatus("wireless", wireless)
		fillstatus("switch", switch)
		fillstatus("vlan", vlan)
		return json.encode(status)
	end
end

function apnetwork(nic)
	local status = {device={}, network={}, wireless={}, switch={}, vlan={}}
	return function() 
		status.device.model = lib.capture(system.get)
		fillstatus("network", network, nic)
		return json.encode(status)
	end
end
